package com.j1ay.forum.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.j1ay.forum.dao.mapper.AnswerMapper;
import com.j1ay.forum.dao.mapper.QuestionMapper;
import com.j1ay.forum.model.pojo.po.Answer;
import com.j1ay.forum.model.dto.params.AnswerParam;
import com.j1ay.forum.model.pojo.po.Question;
import com.j1ay.forum.service.AnswerService;
import com.j1ay.forum.service.QuestionService;
import com.j1ay.forum.service.ThreadService;
import com.j1ay.forum.service.UserService;
import com.j1ay.forum.model.pojo.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author J1ay
 * @Date 2021/12/17 16:04
 * @Description
 */

@Service
public class AnswerServiceImpl implements AnswerService {

    @Autowired(required = false)
    private AnswerMapper answerMapper;

    @Autowired(required = false)
    private QuestionMapper questionMapper;

    @Autowired
    private UserService userService;

    @Autowired
    private QuestionService questionService;

    @Autowired
    private ThreadService threadService;

    // 类型转换 answer -> answerVo
    private List<AnswerVo> copyList(List<Answer> records) {
        List<AnswerVo> answerVoList = new ArrayList<>();
        for (Answer record: records) {
            answerVoList.add(copy(record));
        }
        return answerVoList;
    }

    private AnswerVo copy(Answer answer) {
        AnswerVo answerVo = new AnswerVo();
        BeanUtils.copyProperties(answer, answerVo);
        answerVo.setCreateTime(new DateTime(answer.getCreateTime()).toString("yyyy-MM-dd HH:mm"));
        LoginUserVo userVo = userService.findUserVoById(answer.getUsername());
        answerVo.setLoginUserVo(userVo);
        return answerVo;
    }

    @Override
    public Result findAnswersById(Long questionId) {
        LambdaQueryWrapper<Answer> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(Answer::getQuestionId, questionId)
                .select();
        List<Answer> answerList = answerMapper.selectList(queryWrapper);

        List<AnswerVo> answerVoList = copyList(answerList);
        return Result.success(answerVoList);
    }


    /**
     * 点赞该回答
     * @param answerId
     * @return
     */
    @Override
    public Result toPraiseAnswer(Long answerId) {
        LambdaQueryWrapper<Answer> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(Answer::getId, answerId)
                .select()
                .last("limit 1");
        Answer answer = answerMapper.selectOne(queryWrapper);
        // 放入线程池，进行点赞操作
        threadService.updateANswerPraise(answerMapper, answer);
        return Result.success(null);
    }

    @Override
    public Result replyForQuestion(AnswerParam answerParam) {
        Long questionId = answerParam.getQuestionId();
        String username = answerParam.getUsername();
        String content = answerParam.getContent();

        if (null == questionId || StringUtils.isBlank(username) || StringUtils.isBlank(content)) {
            return Result.fail(ErrorCode.PARAMS_BLANK.getCode(), ErrorCode.PARAMS_BLANK.getMsg());
        }
        Answer answer = new Answer();
        answer.setContent(content);
        answer.setCreateTime(new Date());
        answer.setUsername(username);
        answer.setQuestionId(questionId);

        int res = this.answerMapper.insert(answer);
        if (0 == res) {
            Result.fail(ErrorCode.SESSION_FAILED.getCode(), ErrorCode.SESSION_FAILED.getMsg());
        }
        // 放入线程池，进行问题回答数+1操作
        LambdaQueryWrapper<Question> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(Question::getId, questionId)
                .select()
                .last("limit 1");
        Question question = questionMapper.selectOne(queryWrapper);
        threadService.updateAnswerCount(questionMapper, question);
        return Result.success(null);
    }

    @Override
    public Result getUserAnswer(String username) {
        if (StringUtils.isBlank(username)) {
            return Result.fail(ErrorCode.PARAMS_BLANK.getCode(), ErrorCode.PARAMS_BLANK.getMsg());
        }
        LambdaQueryWrapper<Answer> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(Answer::getUsername, username)
                .select();
        List<Answer> answerList = answerMapper.selectList(queryWrapper);

        List<UserAnswerVo> userAnswerVos = copyUserAnswerList(answerList);
        return Result.success(userAnswerVos);
    }

    private List<UserAnswerVo> copyUserAnswerList(List<Answer> answerList) {
        List<UserAnswerVo> answerVoList = new ArrayList<>();
        for (Answer record: answerList) {
            answerVoList.add(copyUserAnswer(record));
        }
        return answerVoList;
    }

    private UserAnswerVo copyUserAnswer(Answer answer) {
        UserAnswerVo userAnswerVo = new UserAnswerVo();
        BeanUtils.copyProperties(answer, userAnswerVo);
        userAnswerVo.setCreateTime(new DateTime(answer.getCreateTime()).toString("yyyy-MM-dd HH:mm"));
        QuestionVo questionVo = questionService.findQuestionVoById(answer.getQuestionId());
        userAnswerVo.setQuestion(questionVo);
        return userAnswerVo;
    }

    @Override
    public Result deleteAnswer(Long id) {
        if (null == id) {
            return Result.fail(ErrorCode.PARAMS_BLANK.getCode(), ErrorCode.PARAMS_BLANK.getMsg());
        }
//        int res = this.answerMapper.deleteByAnswerId(id);
        int res = answerMapper.deleteById(id);
        if (0 == res) {
            return Result.fail(ErrorCode.SESSION_FAILED.getCode(), ErrorCode.SESSION_FAILED.getMsg());

        }
        return Result.success(null);
    }
}
